import 'package:FlutterStudy/CounterDemo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'WrapDemo.dart';

class ToutiaoDemo extends StatefulWidget {
  @override
  _ToutiaoDemoState createState() => _ToutiaoDemoState();
}

class _ToutiaoDemoState extends State<ToutiaoDemo>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  // 新闻分类标签
  final List<String> _categories = [
    '推荐',
    '热点',
    '视频',
    '娱乐',
    '科技',
    '财经',
    '体育',
    '汽车',
    '时尚',
    '房产',
    '教育',
    '游戏',
    '旅游',
    '军事',
    '历史',
  ];

  @override
  void initState() {
    super.initState();
    /*Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) {
          return WrapDemo(); // 基本路由跳转 参数传递直接在创建组件的时候传递
        },
      ),
    );
    Navigator.pushNamed(context, '/a', arguments: 'Hello'); // 路由命名 及参数传递
    String arg = ModalRoute.of(context)?.settings.arguments as String;*/
    _tabController = TabController(length: _categories.length, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '今日头条',
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
        ),
        backgroundColor: Colors.red,
        elevation: 0,
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(40.0),
          child: Container(
            height: 40.0,
            width: MediaQuery.of(context).size.width,
            color: Colors.pink,
            padding: EdgeInsets.only(left: 0.0),
            child: TabBar(
              controller: _tabController,
              tabAlignment: TabAlignment.center,
              //添加该设置大段间隔消失
              enableFeedback: true,

              indicatorPadding: EdgeInsets.only(left: 0.0),
              overlayColor: WidgetStateProperty.all(Colors.green),
              padding: EdgeInsets.only(left: 0),
              labelPadding: EdgeInsets.only(left: 0, right: 10),

              isScrollable: true,
              // 可滚动
              indicatorColor: Colors.blueAccent,
              indicatorWeight: 3.0,
              indicatorSize: TabBarIndicatorSize.label,
              labelColor: Colors.white,
              labelStyle: TextStyle(
                fontSize: 16.0,
                fontWeight: FontWeight.bold,
              ),
              unselectedLabelColor: Colors.white70,
              unselectedLabelStyle: TextStyle(
                fontSize: 15.0,
                fontWeight: FontWeight.normal,
              ),
              tabs: _categories
                  .map(
                    (category) => Tab(
                      child: Container(
                        child: Text(category),
                        color: Colors.amber,
                      ),
                    ),
                  )
                  .toList(),
            ),
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () {
              Navigator.pushNamed(context, '/second');
              // 搜索功能
            },
          ),
          IconButton(
            icon: Icon(Icons.more_vert),
            onPressed: () {
              // 更多选项
              Navigator.push(
                context,
                CupertinoPageRoute(
                  builder: (BuildContext context) {
                    return CounterDemo();
                  },
                ),
              );
            },
          ),
        ],
      ),
      body: TabBarView(
        controller: _tabController,
        children: _categories
            .map((category) => NewsListPage(category: category))
            .toList(),
      ),
    );
  }
}

// 新闻列表页面
class NewsListPage extends StatefulWidget {
  final String category;

  NewsListPage({required this.category});

  @override
  _NewsListPageState createState() => _NewsListPageState();
}

class _NewsListPageState extends State<NewsListPage> {
  late List<Map<String, dynamic>> _newsList;
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
      GlobalKey<RefreshIndicatorState>();

  @override
  void initState() {
    super.initState();
    _loadNews();
  }

  // 模拟加载新闻数据
  void _loadNews() {
    _newsList = List.generate(20, (index) {
      return {
        'title': '${widget.category}新闻标题 $index - 今日头条为你带来最新资讯',
        'summary': '这是新闻摘要内容，简要介绍新闻的主要内容。新闻摘要通常包含关键信息，吸引读者点击阅读全文。',
        'source': '新闻来源${index + 1}',
        'time': '${DateTime.now().hour}:${DateTime.now().minute}',
        'image': index % 3 == 0 ? 'images/pic6.jpg' : null,
        'isHot': index % 5 == 0,
        'comments': (index * 10 + 5).toString(),
      };
    });
  }

  // 模拟刷新数据
  Future<void> _refreshNews() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      _loadNews();
    });
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      key: _refreshIndicatorKey,
      onRefresh: _refreshNews,
      child: ListView.builder(
        itemCount: _newsList.length + 1,
        itemBuilder: (context, index) {
          if (index == 0) {
            // 顶部 Banner 广告
            return _buildBanner();
          }
          return _buildNewsItem(_newsList[index - 1]);
        },
      ),
    );
  }

  // 构建 Banner
  Widget _buildBanner() {
    return Container(
      height: 120,
      margin: EdgeInsets.all(10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        image: DecorationImage(
          image: AssetImage('images/pic2.jpg'),
          fit: BoxFit.cover,
        ),
      ),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          gradient: LinearGradient(
            colors: [
              Colors.black.withOpacity(0.3),
              Colors.transparent,
              Colors.black.withOpacity(0.3),
            ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        child: Center(
          child: Text(
            '今日头条 - 你关心的才是头条',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }

  // 构建新闻项
  Widget _buildNewsItem(Map<String, dynamic> news) {
    return Card(
      margin: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      elevation: 2,
      child: InkWell(
        onTap: () {
          // 点击新闻项
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('查看新闻: ${news['title']}')));
        },
        child: Padding(
          padding: EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 新闻标题
              Row(
                children: [
                  Expanded(
                    child: Text(
                      news['title'],
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (news['isHot'])
                    Container(
                      margin: EdgeInsets.only(left: 8),
                      padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(2),
                      ),
                      child: Text(
                        '热',
                        style: TextStyle(color: Colors.white, fontSize: 12),
                      ),
                    ),
                ],
              ),

              SizedBox(height: 8),

              // 新闻图片和摘要
              if (news['image'] != null)
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Text(
                        news['summary'],
                        style: TextStyle(fontSize: 14, color: Colors.grey[700]),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    SizedBox(width: 10),
                    ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: Image.asset(
                        news['image'],
                        width: 100,
                        height: 70,
                        fit: BoxFit.cover,
                      ),
                    ),
                  ],
                )
              else
                Text(
                  news['summary'],
                  style: TextStyle(fontSize: 14, color: Colors.grey[700]),
                  maxLines: 4,
                  overflow: TextOverflow.ellipsis,
                ),

              SizedBox(height: 8),

              // 底部信息
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    news['source'],
                    style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                  ),
                  Text(
                    news['time'],
                    style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                  ),
                  Row(
                    children: [
                      Icon(Icons.comment, size: 14, color: Colors.grey[600]),
                      SizedBox(width: 4),
                      Text(
                        news['comments'],
                        style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 视频新闻特殊页面
class VideoNewsPage extends StatelessWidget {
  final String category;

  VideoNewsPage({required this.category});

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: () async {
        await Future.delayed(Duration(seconds: 2));
      },
      child: GridView.builder(
        padding: EdgeInsets.all(10),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          childAspectRatio: 0.8,
        ),
        itemCount: 20,
        itemBuilder: (context, index) {
          return Card(
            elevation: 2,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Stack(
                  children: [
                    Container(
                      height: 100,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('images/pic3.jpg'),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    Positioned(
                      right: 5,
                      bottom: 5,
                      child: Container(
                        padding: EdgeInsets.all(2),
                        color: Colors.black54,
                        child: Text(
                          '0${index ~/ 6}:${(index % 6) * 10}',
                          style: TextStyle(color: Colors.white, fontSize: 12),
                        ),
                      ),
                    ),
                    Center(
                      child: Icon(
                        Icons.play_circle_fill,
                        color: Colors.white.withOpacity(0.8),
                        size: 40,
                      ),
                    ),
                  ],
                ),
                Padding(
                  padding: EdgeInsets.all(8),
                  child: Text(
                    '$category视频标题 $index',
                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '${index * 100 + 50}次播放',
                        style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      ),
                      Icon(Icons.more_vert, size: 16, color: Colors.grey[600]),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

// 使用示例
void main() {
  runApp(MaterialApp(home: ToutiaoDemo(), debugShowCheckedModeBanner: false));
}
